package com.imooc.course.server.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imooc.course.server.dao.RoleUserDao;
import com.imooc.course.server.dao.my.MyRoleUserDao;
import com.imooc.course.server.dto.RoleResourceDto;
import com.imooc.course.server.dto.RoleUserDto;
import com.imooc.course.server.dto.PageDto;
import com.imooc.course.server.entity.RoleResource;
import com.imooc.course.server.entity.RoleResourceExample;
import com.imooc.course.server.entity.RoleUser;
import com.imooc.course.server.entity.RoleUserExample;
import com.imooc.course.server.service.RoleUserService;
import com.imooc.course.server.utils.CopyUtil;
import com.imooc.course.server.utils.UuidUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service("roleUserService")
public class RoleUserServiceImpl implements RoleUserService {

    private static final Logger log = LoggerFactory.getLogger(RoleUserServiceImpl.class);

    @Resource(name = "roleUserDao")
    private RoleUserDao roleUserDao;

    @Resource(name = "myRoleUserDao")
    private MyRoleUserDao myRoleUserDao;

    /**
     * 列表查询
     * @param pageDto
     */
    @Override
    public void getList(PageDto pageDto) {
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());

        RoleUserExample roleUserExample = new RoleUserExample();
        List<RoleUser> roleUserList = roleUserDao.selectByExample(roleUserExample);

        PageInfo<RoleUser> roleUserPageInfo = new PageInfo<>(roleUserList);
        pageDto.setTotal(roleUserPageInfo.getTotal());

        List<RoleUserDto> roleUserDtoList = CopyUtil.copyList(roleUserList, RoleUserDto.class);

        pageDto.setList(roleUserDtoList);
    }

    /**
     * 保存，id有值为更新，id无值为新增
     * @param roleUserDto
     */
    @Override
    public void save(RoleUserDto roleUserDto) {
        RoleUser copy = CopyUtil.copy(roleUserDto, RoleUser.class);
        String id = roleUserDto.getId() != null ? roleUserDto.getId().trim() : roleUserDto.getId();
        if (StringUtils.isEmpty(id)) {
            this.addRoleUser(copy);
        }else{
            this.updateRoleUser(copy);
        }
    }

    private void updateRoleUser(RoleUser copy) {
        roleUserDao.updateByPrimaryKeySelective(copy);
    }

    private void addRoleUser(RoleUser copy) {
        copy.setId(UuidUtil.getShortUuid());
        roleUserDao.insertSelective(copy);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(String id) {
        roleUserDao.deleteByPrimaryKey(id);
    }

    /**
     * 授予用户角色权限
     * @param roleUserDto
     */
    @Transactional
    @Override
    public void authorization(RoleUserDto roleUserDto) {

        String roleId = roleUserDto.getRoleId();
        List<String> userIdList = roleUserDto.getUserIdList();

        if (CollectionUtils.isEmpty(userIdList)) {
            RoleUserExample example1 = new RoleUserExample();
            example1.createCriteria().andRoleIdEqualTo(roleId);
            roleUserDao.deleteByExample(example1);
            return ;
        }

        RoleUserExample example = new RoleUserExample();
        example.createCriteria().andRoleIdEqualTo(roleId);
        List<RoleUser> roleUsers = roleUserDao.selectByExample(example);

        Set<String> deleteSet = new HashSet<>();
            for (int i = 0; i < userIdList.size(); i++) {
                for (int j = 0; j < roleUsers.size(); j++) {
                    if (!userIdList.get(i).equals(roleUsers.get(j).getUserId())) {
                        deleteSet.add(roleUsers.get(j).getUserId());
                    }
                }
            }
        List<String> collect = new ArrayList<>(deleteSet);

        RoleUserExample example1 = new RoleUserExample();
        example1.createCriteria().andRoleIdEqualTo(roleId);
        example1.createCriteria().andUserIdIn(collect);
        roleUserDao.deleteByExample(example1);

        List<RoleUser> list = userIdList.stream()
                .map((id) -> {
                    RoleUser roleUser = new RoleUser();
                    roleUser.setId(UuidUtil.getShortUuid());
                    roleUser.setRoleId(roleId);
                    roleUser.setUserId(id);
                    return roleUser;
                })
                .collect(Collectors.toList());

        myRoleUserDao.batchInsert(list);

    }

    @Override
    public List<RoleUserDto> getListByRoleId(String roleId) {
        RoleUserExample example = new RoleUserExample();
        example.createCriteria().andRoleIdEqualTo(roleId);
        List<RoleUser> roleUsers = roleUserDao.selectByExample(example);
        return CopyUtil.copyList(roleUsers,RoleUserDto.class);
    }
}
